//index.js
const app = getApp()

Page({
  data: {
    access_token: '',
    prodoctList: []
  },
  onLoad: function () {
    this.getAccessToken()
  },
  // 云函数获取AccessToken
  getAccessToken: function (a) {
    wx.showLoading({
      title: '商品加载中',
    })
    var that = this
    // 调用云函数
    wx.cloud.callFunction({
      name: 'api',
      data: {
        method: 'getAccessToken'
      },
      success: res => {
        console.log('[云函数] getAccessToken: ', res.result)
        that.setData({
          access_token: res.result.access_token
        })
        that.getProductList(res.result.access_token) 
      },
      fail: err => {
        wx.hideLoading({
          success: (res) => {},
        })
        console.error('[云函数] [getAccessToken] 调用失败', err)
      }
    })
  },
  
  // 云函数获取商品列表
  getProductList: function (e) {
    var that = this
    // 调用云函数
    wx.cloud.callFunction({
      name: 'api',
      data: {
        method: 'getProductList',
        access_token: e,
        from: '1',
        limit: '100'
      },
      success: res => {
        console.log('[云函数] getProductList: ', res.result)
        that.setData({
          prodoctList: res.result.productList
        })
        wx.hideLoading({
          success: (res) => {},
        })
      },
      fail: err => {
        console.error('[云函数] [getProductList] 调用失败', err)
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })
  },

  //进入商品对应小商店
  gotoShop: function (e) {
    var productId = e.currentTarget.dataset.productid;
    var appId = e.currentTarget.dataset.shopappid;
    var a = {
      "productId":productId,
      "appId":appId
    }
    var productList = [a]
    var that = this

    wx.showLoading({
      title: '商品加载中',
    })
    wx.cloud.callFunction({
      name: 'api',
      data: {
        method: 'getProductGenerate',
        access_token: that.data.access_token,
        productList: productList,
      },
      success: res => {
        wx.hideLoading({
          success: (res) => {},
        })
        console.log('[云函数] gotoShop: ', res)
        wx.navigateToMiniProgram({
          appId: res.result.list[0].shareInfo.appId,
          path:res.result.list[0].shareInfo.path
        })
      },
      fail: err => {
        console.error('[云函数] [gotoShop] 调用失败', err)
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })
  }

})